package com.hamu.service.impl;

import com.aliyun.oss.ServiceException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hamu.mapper.ArticleTagMapper;
import com.hamu.mapper.TagMapper;
import com.hamu.pojo.Article;
import com.hamu.pojo.PageBean;
import com.hamu.pojo.Result;
import com.hamu.pojo.Tag;
import com.hamu.service.TagService;
import com.hamu.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public void add(Tag tag) {
        tag.setCreatedTime(LocalDateTime.now());
        Map<String, Object> user = ThreadLocalUtil.get();
        Integer userId = (Integer) user.get("id");
        tag.setCreateUser(userId);
        tagMapper.add(tag);
    }

    @Override
    public List<Tag> list() {
        Map<String, Object> user = ThreadLocalUtil.get();
        Integer userId = (Integer) user.get("id");
        return tagMapper.list(userId);
    }

    @Override
    public List<Tag> listAll() {
        return tagMapper.listAll();
    }

    @Override
    public Tag findById(Integer tagId) {
        return tagMapper.findById(tagId);
    }

    @Override
    public void update(Tag tag) {
        tagMapper.update(tag);
    }

    @Override
    public void delete(Integer tagId) {
        // 检查是否被文章使用
        if(articleTagMapper.countByTagId(tagId) > 0){
            throw new ServiceException("标签已被使用，无法删除");
        }
        tagMapper.delete(tagId);
    }

    @Override
    public PageBean<Tag> searchList(Integer pageNum, Integer pageSize, String query) {
        PageBean<Tag> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Tag> tags = tagMapper.searchTags(query);
        Page<Tag> p = (Page<Tag>) tags;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
}